class MyPromise {

    constructor(executor) {
        //状态有三种 pending fulfilled rejected
        this.state = 'pending'
        //成功的值
        this.value = undefined
        //失败的原因
        this.reason = undefined
        //成功回调数组
        this.resolveCallbacks=[]
        //失败回调数组
        this.rejectCallbacks=[]
        let resolve = (value) => {
            if (this.state === 'pending') {
                this.value = value
                // resolve调用后，state转化为成功态
                this.state = 'fulfilled';
                this.resolveCallbacks.forEach(fn=>fn())
            }
        }
        let reject = (reason) => {
            if (this.state === 'pending') {
                this.reason = reason
                // resolve调用后，state转化为成功态
                this.state = 'rejected';
                this.rejectCallbacks.forEach(fn=>fn())
            }
        }
        try {
            executor(resolve, reject)
        } catch (error) {
            reject(error)
        }
        
    }

    then(onFulfill,onReject){

        if(this.state==='fulfilled'){
            onFulfill(this.value)
        }
        if(this.state==='rejected'){
            onReject(this.reason)
        }
        //解决settimeout 
        if(this.state==='pending'){
            this.resolveCallbacks.push(()=>{
                onFulfill(this.value)
            })

            this.rejectCallbacks.push(()=>{
                onReject(this.reason)
            })
        }
    }
}